/**
 * Created by Administrator on 2017/4/1.
 */
"use strict";
swan_pc
    .controller("CalendarController",function($scope,$rootScope,ClipByLevel,Clip,ngDialog,Friends,UserClip,UserContactsSelect,UserOppSelect,TimeCheck,$timeout){
        //主列表展示
        $scope.state=1;
        $scope.changeState = function(option){
            $scope.state = option;
            if(option==1){
                $scope.loadClip();
            }else if(option==2){
                $scope.toDoState=1;
                $scope.loadToDo();
            }else if(option==3){
                $scope.agendaState=1;
                $scope.loadAgenda();
            }else if(option==4){
                $scope.selectFriend();
            }
        };
        $scope.currentFriendId=null;
        $scope.currentFriendName="";
        //待办列表展示
        $scope.toDoState=1;
        $scope.changeToDoState = function(option){
            $scope.toDoState = option;
            $scope.loadToDo();
        };
        $scope.displayToDo=[];
        $scope.loadToDo = function(){
            ClipByLevel.query({level:1},function(result){
                $scope.displayToDo=[];
                $scope.todayToDo=[];
                $scope.delayToDo=[];
                $scope.allToDo=result;
                _.forEach(result,function(data){
                    var startDate = new Date(data.startTime).toLocaleDateString();
                    var today = new Date().toLocaleDateString();
                    if(startDate == today){
                        $scope.todayToDo.push(data);
                    }
                    if(data.isDelayed){
                        $scope.delayToDo.push(data);
                    }
                });
                switch($scope.toDoState){
                    case 1:
                        $scope.displayToDo=$scope.todayToDo;
                        break;
                    case 2:
                        $scope.displayToDo=$scope.allToDo;
                        break;
                    case 3:
                        $scope.displayToDo=$scope.delayToDo;
                        break;
                }
            })
        };
        //checkbox实现相关
        //创建变量用来保存选中结果
        $scope.selected = [];
        var updateSelected = function (action, id) {
            if (action == 'add' && $scope.selected.indexOf(id) == -1) $scope.selected.push(id);
            if (action == 'remove' && $scope.selected.indexOf(id) != -1) $scope.selected.splice($scope.selected.indexOf(id), 1);
        };
        //更新某一列数据的选择
        $scope.updateSelection = function ($event, id) {
            var checkbox = $event.target;
            var action = (checkbox.checked ? 'add' : 'remove');
            updateSelected(action, id);
        };
        //全选操作
        $scope.selectAll = function ($event) {
            var checkbox = $event.target;
            var action = (checkbox.checked ? 'add' : 'remove');
            for (var i = 0; i < $scope.displayToDo.length; i++) {
                var toDo = $scope.displayToDo[i];
                updateSelected(action, toDo.id);
            }
        };
        $scope.isSelected = function (id) {
            return $scope.selected.indexOf(id) >= 0;
        };
        $scope.isSelectedAll = function () {
            return $scope.selected.length === $scope.displayToDo.length;
        };
        //星期展示
        $scope.weekDayDisplay=function(date){
            var str1="星期";
            var date1 = new Date(date);
            var week = date1.getDay();
            switch (week) {
                case 0 :
                    str1 += "日";
                    break;
                case 1 :
                    str1 += "一";
                    break;
                case 2 :
                    str1 += "二";
                    break;
                case 3 :
                    str1 += "三";
                    break;
                case 4 :
                    str1 += "四";
                    break;
                case 5 :
                    str1 += "五";
                    break;
                case 6 :
                    str1 += "六";
                    break;
            }
            return str1;
        };
        //排序
        $scope.orderByKey=function(key,eve){
            $scope.reverse = ($scope.orderKey === key) ? !$scope.reverse : false;
            $scope.orderKey = key;
        };
        $scope.orderList=function(item){
            return item[$scope.orderKey];
        };
        //事项列表展示
        $scope.agendaState=1;
        $scope.changeAgendaState = function(option){
            $scope.agendaState=option;
            $scope.loadAgenda();
        };
        $scope.displayAgenda=[];
        $scope.loadAgenda = function(){
            Clip.query({size:5000,page:0},function(result){
                $scope.draftAgenda=[];
                $scope.confirmAgenda=[];
                $scope.closedAgenda=[];
                $scope.delayAgenda=[];
                _.forEach(result,function(data){
                    if(data.status == "DRAFT"){
                        $scope.draftAgenda.push(data);
                    }
                    if(data.status == "CONFIRM"){
                        $scope.confirmAgenda.push(data);
                    }
                    if(data.status == "CLOSED"){
                        $scope.closedAgenda.push(data);
                    }
                    if(data.isDelayed){
                        $scope.delayAgenda.push(data);
                    }
                });
                switch($scope.agendaState){
                    case 1:
                        $scope.displayAgenda = $scope.draftAgenda;
                        break;
                    case 2:
                        $scope.displayAgenda = $scope.confirmAgenda;
                        break;
                    case 3:
                        $scope.displayAgenda = $scope.closedAgenda;
                        break;
                    case 4:
                        $scope.displayAgenda = $scope.delayAgenda;
                        break;
                }
            })
        };
        //checkbox实现相关
        //创建变量用来保存选中结果
        $scope.selected1 = [];
        var updateSelected1 = function (action, id) {
            if (action == 'add' && $scope.selected1.indexOf(id) == -1) $scope.selected1.push(id);
            if (action == 'remove' && $scope.selected1.indexOf(id) != -1) $scope.selected1.splice($scope.selected1.indexOf(id), 1);
        };
        //更新某一列数据的选择
        $scope.updateSelection1 = function ($event, id) {
            var checkbox = $event.target;
            var action = (checkbox.checked ? 'add' : 'remove');
            updateSelected1(action, id);
        };
        //全选操作
        $scope.selectAll1 = function ($event) {
            var checkbox = $event.target;
            var action = (checkbox.checked ? 'add' : 'remove');
            for (var i = 0; i < $scope.displayAgenda.length; i++) {
                var agenda = $scope.displayAgenda[i];
                updateSelected1(action, agenda.id);
            }
        };
        $scope.isSelected1 = function (id) {
            return $scope.selected1.indexOf(id) >= 0;
        };
        $scope.isSelectedAll1 = function () {
            return $scope.selected1.length === $scope.displayAgenda.length;
        };

        //我的日程列表展示
        $scope.initCalendar = function(){
            var date = new Date();
            var d = date.getDate();
            var m = date.getMonth();
            var y = date.getFullYear();

            var calendar = $('#calendar').fullCalendar({
                header: {
                    left: '    prev today next',
                    center: 'title',
                    right: 'agendaWeek,month     '
                },
                buttonText:{
                    today:"今日",
                    month:"月",
                    agendaWeek:"周"
                },
                weekNumbers:true,
                aspectRatio:2,
                defaultView:"agendaWeek",
                allDaySlot:false,
                axisFormat:"HH:mm",
                selectHelper: true,
                select: function(start, end, allDay) {
                    var title = prompt('Event Title:');
                    if (title) {
                        calendar.fullCalendar('renderEvent',
                            {
                                title: title,
                                start: start,
                                end: end,
                                allDay: allDay
                            },
                            true // make the event "stick"
                        );
                    }
                    calendar.fullCalendar('unselect');
                },
                droppable: true, // this allows things to be dropped onto the calendar !!!
                drop: function(date, allDay) { // this function is called when something is dropped
                    var originalEventObject = $(this).data('eventObject');
                    var copiedEventObject = $.extend({}, originalEventObject);
                    copiedEventObject.start = date;
                    copiedEventObject.allDay = allDay;
                    // is the "remove after drop" checkbox checked?
                    if ($('#drop-remove').is(':checked')) {
                        // if so, remove the element from the "Draggable Events" list
                        $(this).remove();
                    }
                },

                eventClick:function(event,jsEvent,view){
                    Clip.get({clipid:event.id},function(result){
                        $scope.editClip(result,2);
                    });
                },
                dayClick:function(date, allDay, jsEvent, view){
                    $scope.editClip(date,1);
                }
            })
        };
        $scope.initCalendar();
        $scope.loadClip = function(){
            var login = $rootScope.login;
            $scope.clips=[];
            $("#calendar").fullCalendar("removeEvents");
            ClipByLevel.query({level:0}, function(result) {
                $scope.clips = result;
                _.forEach($scope.clips,function(data){
                    var startDate = new Date(data.startTime);
                    var endDate = new Date(data.endTime);
                    if(data.status=="DRAFT" || data.status=="CONFIRM"){
                        if(data.isDelayed){
                            var events=[{
                                title:data.name,
                                start:startDate,
                                end:endDate,
                                backgroundColor:Theme.colors.red,
                                id:data.id,
                                bookerId:data.bookerId,
                                allDay:false,
                                block:true
                            }]
                        }else{
                            if(data.bookerId!=null){
                                var events=[{
                                    title:data.name,
                                    start:startDate,
                                    end:endDate,
                                    backgroundColor:Theme.colors.orange,
                                    id:data.id,
                                    bookerId:data.bookerId,
                                    allDay:false,
                                    block:true
                                }]
                            }else{
                                var events=[{
                                    title:data.name,
                                    start:startDate,
                                    end:endDate,
                                    backgroundColor:Theme.colors.gray,
                                    id:data.id,
                                    bookerId:data.bookerId,
                                    allDay:false,
                                    block:true
                                }]
                            }
                        }
                    }
                    $("#calendar").fullCalendar("addEventSource", events);
                });
            });
        };
        $scope.loadClip();
        /*编辑日程（new and edit）*/
        $scope.editClip = function(clickTime,option){
            ngDialog.open({
                templateUrl:"scripts/components/calendar/editClip.html",
                scope:$scope,
                overlay:false,
                closeByDocument:false,
                controller:["$scope",function(){
                    $scope.option = option;
                    $scope.selectedRemindList=[];
                    if(option==1 || option==3){
                        $scope.clip = {
                            id:null,
                            name:null,
                            startTime:null,
                            endTime:null,
                            isSecret:0,
                            relatedContact:null,
                            relatedOpp:null,
                            isImportant:null,
                            remind:null,
                            status:null,
                            bookerId:null,
                            level:0
                        };
                        if(option==1){
                            $scope.clip.status = "CONFIRM";
                        }else{
                            $scope.clip.status = "DRAFT";
                            $scope.clip.bookerId = $rootScope.presentAccountInfo.id;
                        }

                        $scope.clip.startTime = new Date(clickTime);
                        $scope.clip.endTime = new Date(clickTime);
                        $scope.clip.endTime.setMinutes($scope.clip.endTime.getMinutes()+45);
                    }else if(option==2){
                        //clip update
                        $scope.clip = clickTime;
                        if($scope.clip.remind!=null){
                            $scope.selectedRemindList = $scope.clip.remind.split(",");
                        }
                        $scope.clip.startTime = new Date($scope.clip.startTime);
                        $scope.clip.endTime = new Date($scope.clip.endTime);
                    }else if(option==5){
                        //todo update
                        $scope.clip = clickTime;
                        if($scope.clip.remind!=null){
                            $scope.selectedRemindList = $scope.clip.remind.split(",");
                        }
                        $scope.clip.startTime = new Date($scope.clip.startTime);
                        $scope.clip.endTime = new Date($scope.clip.endTime);
                    }else if(option==4){
                        $scope.clip = {
                            id:null,
                            name:null,
                            startTime:new Date(),
                            endTime:new Date(),
                            isSecret:0,
                            relatedContact:null,
                            relatedOpp:null,
                            isImportant:null,
                            status:"CONFIRM",
                            level:1
                        };
                    }

                    $scope.selectDisplay = -1;
                    $scope.changeSelectDisplay = function(option){
                        $scope.selectDisplay = option;
                    };
                    $scope.getUserContact = function(){
                        UserContactsSelect.query(function(result){
                            $scope.userContact = result;
                        })
                    };
                    $scope.getUserContact();
                    $scope.choseThisContact = function(name,id){
                        var str = id + ":" + name;
                        $scope.clip.relatedContact = str;
                    };
                    $scope.returnContactId = function(option){
                        if($scope.clip.relatedContact==null){
                            return null;
                        }
                        var str1 = $scope.clip.relatedContact.split(":");
                        if(option==1){
                            return str1[0];
                        }else{
                            return str1[1];
                        }

                    };
                    $scope.getOpp = function(){
                        UserOppSelect.query(function(result){
                            $scope.userOpp = result;
                        })
                    };
                    $scope.getOpp();
                    $scope.choseThisOpp = function(name,id){
                        var str = id + ":" + name;
                        $scope.clip.relatedOpp = str;
                    };
                    $scope.returnOppId = function(option){
                        if($scope.clip.relatedOpp == null){
                            return null;
                        }
                        var str2 = $scope.clip.relatedOpp.split(":");
                        if(option==1){
                            return str2[0];
                        }else{
                            return str2[1];
                        }
                    };

                    $scope.remindList = [
                        {
                            name:"事项发生时",
                            value:"0"
                        },
                        {
                            name:"开始前五分钟",
                            value:"300"
                        },
                        {
                            name:"开始前十五分钟",
                            value:"900"
                        },
                        {
                            name:"开始前半小时",
                            value:"1800"
                        },
                        {
                            name:"开始前一小时",
                            value:"3600"
                        },
                        {
                            name:"开始前两小时",
                            value:"7200"
                        },
                        {
                            name:"开始前半日",
                            value:"43200"
                        },
                        {
                            name:"开始前一日",
                            value:"86400"
                        }
                    ];
                    $scope.choseThisRemind = function(value){
                        var find = false;
                        _.forEach($scope.selectedRemindList,function(data,index){
                            if(data==value){
                                $scope.selectedRemindList.splice(index,1);
                                find = true;
                            }
                        });
                        if(!find){
                            $scope.selectedRemindList.push(value);
                        }
                        var str = "";
                        _.forEach($scope.selectedRemindList,function(data){
                            str = str + data + ",";
                        });
                        str = str.substring(0,str.length-1);
                        $scope.clip.remind = str;
                    };
                    $scope.checkRemindList = function(value){
                        var str = 0;
                        _.forEach($scope.selectedRemindList,function(data){
                            //console.log(value + " " +data);
                            if(data==value){
                                str = 1;
                            }
                        });
                        return str;
                    };
                    $scope.displayRemindString = function(){
                        var str = "";
                        _.forEach($scope.selectedRemindList,function(data){
                            switch(data){
                                case "0":
                                    str = str + $scope.remindList[0].name + ",";
                                    break;
                                case "300":
                                    str = str + $scope.remindList[1].name + ",";
                                    break;
                                case "900":
                                    str = str + $scope.remindList[2].name + ",";
                                    break;
                                case "1800":
                                    str = str + $scope.remindList[3].name + ",";
                                    break;
                                case "3600":
                                    str = str + $scope.remindList[4].name + ",";
                                    break;
                                case "7200":
                                    str = str + $scope.remindList[5].name + ",";
                                    break;
                                case "43200":
                                    str = str + $scope.remindList[6].name + ",";
                                    break;
                                case "86400":
                                    str = str + $scope.remindList[7].name + ",";
                                    break;
                            }
                        });
                        str = str.substring(0,str.length-1);
                        return str;
                    };

                    $scope.importantList = [
                        {
                            name:"一般",
                            value:0
                        },
                        {
                            name:"重要",
                            value:1
                        }
                    ];
                    $scope.returnImportance = function(){
                        if($scope.clip.isImportant==null){
                            return null;
                        }else if($scope.clip.isImportant==0){
                            return "一般";
                        }else if($scope.clip.isImportant==1){
                            return "重要";
                        }
                    };
                    $scope.saveEdit = function(){
                        if(option==4 || option==5){
                            $scope.clip.startTime.setHours(0);
                            $scope.clip.startTime.setMinutes(0);
                            $scope.clip.startTime.setSeconds(0);
                            $scope.clip.endTime.setHours(23);
                            $scope.clip.endTime.setMinutes(59);
                            $scope.clip.endTime.setSeconds(0);
                            Clip.save($scope.clip,function(result){
                                ngDialog.close();
                                $scope.loadToDo();
                            },function(result){
                            })
                        }else{
                            var flag = TimeCheck.timecheck($scope.clip.startTime, $scope.clip.endTime);
                            var startDate = new Date($scope.clip.startTime);
                            if (flag == 1) {
                                swal("日程不能短于45分钟");
                            }
                            if (flag == 3) {
                                swal("结束时间不得早于开始时间");
                            }
                            if(flag==2){
                                if(option==1){
                                    Clip.save($scope.clip,function(result){
                                        ngDialog.close();
                                        $scope.loadClip();
                                        $timeout(function(){
                                            $("#calendar").fullCalendar("gotoDate",startDate.getFullYear() [startDate.getMonth()[startDate.getDate()]]);
                                        },1000);

                                        console.log(result);
                                    },function(result){
                                        console.log(result);
                                    })
                                }else if(option==2){
                                    Clip.update($scope.clip,function(result){
                                        ngDialog.close();
                                        $scope.loadClip();
                                        $timeout(function(){
                                            $("#calendar").fullCalendar("gotoDate",startDate.getFullYear() [startDate.getMonth()[startDate.getDate()]]);
                                        },1000);
                                    },function(result){})
                                }else if(option==3){
                                    UserClip.save({id:$scope.$parent.currentFriendId},$scope.clip,function(result){
                                        ngDialog.close();
                                        $scope.loadFriendClip($scope.$parent.currentFriendId);
                                        $timeout(function(){
                                            $("#calendar1").fullCalendar("gotoDate",startDate.getFullYear() [startDate.getMonth()[startDate.getDate()]]);
                                        },1000);
                                    })
                                }
                            }
                            console.log($scope.clip);
                        }
                    };

                    $scope.cancelEdit = function(){
                        ngDialog.close();
                    }
                }]
            })
        };
        //查看好友日程
        $scope.selectFriend = function(){
            Friends.query(function(result){
                $scope.friends=result;
                //console.log(result);
                ngDialog.open({
                    templateUrl:"scripts/components/calendar/friendSelect.html",
                    scope:$scope,
                    overlay:false,
                    closeByDocument:false,
                    controller:["$scope",function(){
                        $scope.choseFriend = function(id,name){
                            //console.log(name);
                            $scope.$parent.currentFriendId = id;
                            $scope.$parent.currentFriendName = name;
                            ngDialog.closeAll();
                            $scope.loadFriendClip(id,name);
                        }
                    }]
                })
            })
        };

        $scope.loadFriendClip = function(id,name){
            $scope.currentFriendName = name;
            UserClip.query({id:id},function(result){
                $scope.friendClips = result;
                $("#calendar1").fullCalendar("removeEvents");
                _.forEach(result,function(data){
                    var startDate = new Date(data.startTime);
                    var endDate = new Date(data.endTime);
                    if(data.level==0){
                        if(data.isDelayed){
                            var event=[{
                                title:data.name,
                                start:startDate,
                                end:endDate,
                                backgroundColor:Theme.colors.red,
                                id:data.id,
                                bookerId:data.bookerId,
                                allDay:false,
                                block:true
                            }]
                        }else{
                            if(data.bookerId!=null){
                                var event=[{
                                    title:data.name,
                                    start:startDate,
                                    end:endDate,
                                    backgroundColor:Theme.colors.orange,
                                    id:data.id,
                                    bookerId:data.bookerId,
                                    allDay:false,
                                    block:true
                                }]
                            }else{
                                var event=[{
                                    title:data.name,
                                    start:startDate,
                                    end:endDate,
                                    backgroundColor:Theme.colors.gray,
                                    id:data.id,
                                    bookerId:data.bookerId,
                                    allDay:false,
                                    block:true
                                }]
                            }
                        }
                        $("#calendar1").fullCalendar("addEventSource", event);
                    }
                })
            })
        };
        $scope.initCalendar1 = function(){
            var date = new Date();
            var d = date.getDate();
            var m = date.getMonth();
            var y = date.getFullYear();

            var calendar = $('#calendar1').fullCalendar({
                header: {
                    left: '    prev today next',
                    center: 'title',
                    right:'none'
                },
                buttonText:{
                    today:"今日"
                },
                weekNumbers:true,
                aspectRatio:2,
                defaultView:"agendaWeek",
                allDaySlot:false,
                axisFormat:"HH:mm",
                selectHelper: true,
                select: function(start, end, allDay) {
                    var title = prompt('Event Title:');
                    if (title) {
                        calendar.fullCalendar('renderEvent',
                            {
                                title: title,
                                start: start,
                                end: end,
                                allDay: allDay
                            },
                            true // make the event "stick"
                        );
                    }
                    calendar.fullCalendar('unselect');
                },
                droppable: true, // this allows things to be dropped onto the calendar !!!
                drop: function(date, allDay) { // this function is called when something is dropped
                    var originalEventObject = $(this).data('eventObject');
                    var copiedEventObject = $.extend({}, originalEventObject);
                    copiedEventObject.start = date;
                    copiedEventObject.allDay = allDay;
                    // is the "remove after drop" checkbox checked?
                    if ($('#drop-remove').is(':checked')) {
                        // if so, remove the element from the "Draggable Events" list
                        $(this).remove();
                    }
                },

                eventClick:function(event,jsEvent,view){
                },
                dayClick:function(date, allDay, jsEvent, view){
                    $scope.editClip(date,3);
                }
            })
        };
        $scope.initCalendar1();

        $scope.newClip = function(){

        }


    });